package cn.pconline.officialclub.service;

import cn.pconline.autoclub.util.Pager;
import cn.pconline.officialclub.entity.OClub;
import cn.pconline.officialclub.entity.OClubTag;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.gelivable.dao.SqlBuilder;

/**
 *
 * @author xulin
 */
public class OClubTagService extends ServiceKit {

    public Pager<OClubTag> pagerQuery(int pageNo, int pageSize) {
        SqlBuilder sql = new SqlBuilder();
        sql.appendSql("select tag_id from ").appendSql(getTableName(OClubTag.class));
        return pagerService.pager(OClubTag.class, sql, pageNo, pageSize);
    }

    public long create(OClubTag oClubTag) {
        return geliDao.create(oClubTag);
    }

    public int update(OClubTag oClubTag) {
        return geliDao.update(oClubTag);
    }

    public int delete(OClubTag oClubTag) {
        return geliDao.delete(oClubTag, oClubTag.getTagId());
    }

    public boolean isExistTagId(long tagId) {
        SqlBuilder sql = new SqlBuilder();
        sql.appendSql("select count(1) from ").appendSql(getTableName(OClubTag.class)).appendSql(" where tag_id = ").appendValue(tagId);
        return count(sql) > 0;
    }

    public List<OClubTag> queryTags() {
        SqlBuilder sql = new SqlBuilder();
        sql.appendSql("select tag_id from ").appendSql(getTableName(OClubTag.class));
        return geliDao.list(OClubTag.class, sql.getSql(), sql.getValues());
    }

    /**
     * 品牌车友会批量读取分类标签
     *
     * @param oClubs
     * @return
     */
    public List<OClub> loadTags(List<OClub> oClubs, List<OClubTag> tags) {
        if (oClubs == null || oClubs.isEmpty()) {
            return oClubs;
        }
        Map<Long, OClubTag> map = parseMap(tags);
        for (OClub oClub : oClubs) {
            oClub.setTag(map.get(oClub.getTagId()));
        }
        return oClubs;
    }

    private Map<Long, OClubTag> parseMap(List<OClubTag> tags) {
        Map<Long, OClubTag> map = new HashMap<Long, OClubTag>();
        if (tags != null && !tags.isEmpty()) {
            for (OClubTag tag : tags) {
                map.put(tag.getTagId(), tag);
            }
        }
        return map;
    }
}
